package n60_unsafe;

import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author fu
 * @date 2022-02-19 18:28
 *
 *
 */
public class T2_Unsafe_cas_操作对象修改属性 {
    public static void main(String[] args) throws NoSuchFieldException {

        Unsafe unsafe = T1_UnsafeAccessor_非常底层的操作内存和线程方法.getUnsafe();

        Field id = Student.class.getDeclaredField("id");
        Field name = Student.class.getDeclaredField("name");
// 获得成员变量的偏移量
        long idOffset = unsafe.objectFieldOffset(id);
        long nameOffset = unsafe.objectFieldOffset(name);
        Student student = new Student();
// 使用 cas 方法替换成员变量的值
        unsafe.compareAndSwapInt(student, idOffset, 0, 20); // 返回 true
        unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); // 返回 true
        System.out.println(student);
    }
}

@Data
class Student {
    volatile int id;
    volatile String name;
}